#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
/*
 * 执行编译/执行命令 gcc ./sqlite_test.c -o sqlite_test -lsqlite3 && ./sqlite_test
 */
void update_callback(void *arg, int operation, const char *dbname, const char *tblname, sqlite3_int64 rowid) {
    const char *op_str = "UNKNOWN";
    if (operation == SQLITE_INSERT) op_str = "INSERT";
    else if (operation == SQLITE_UPDATE) op_str = "UPDATE";
    else if (operation == SQLITE_DELETE) op_str = "DELETE";

    printf("[HOOK] Operation: %s on table '%s', rowid: %lld\n", op_str, tblname, rowid);
}

int main() {
    sqlite3 *db;
    char *errmsg = NULL;

    if (sqlite3_open("test.db", &db)) {
        fprintf(stderr, "Can't open DB: %s\n", sqlite3_errmsg(db));
        return 1;
    }

    sqlite3_update_hook(db, update_callback, NULL);

    const char *create_sql =
        "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);";
    if (sqlite3_exec(db, create_sql, 0, 0, &errmsg) != SQLITE_OK) {
        fprintf(stderr, "Create table error: %s\n", errmsg);
        sqlite3_free(errmsg);
    }

    const char *op_sql =
        "INSERT INTO users (name, age) VALUES ('Alice', 30);"
        "INSERT INTO users (name, age) VALUES ('Tom', 35);"
        "INSERT INTO users (name, age) VALUES ('Jerry', 25);";
        // "UPDATE users SET age = 31 WHERE name = 'Alice';"
        // "DELETE FROM users WHERE name = 'Alice';";
    if (sqlite3_exec(db, op_sql, 0, 0, &errmsg) != SQLITE_OK) {
        fprintf(stderr, "Op SQL error: %s\n", errmsg);
        sqlite3_free(errmsg);
    }

    sqlite3_close(db);
    return 0;
}
